package com.wanshi.servlet;

import com.wanshi.entity.User;
import com.wanshi.service.UserService;
import com.wanshi.utils.MD5Utils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/regist")
public class regist extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //判断验证码是否正确  获取用户提交的   获取session中保存的
        String valistr = request.getParameter("valistr");
        String code = (String) request.getSession().getAttribute("code");

        if(valistr == null || !valistr.equals(code)){
            //
            request.setAttribute("error", "验证码错误");
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
            return;
        }

        //1 获取表单提交数据
        //注册
        //获取数据  封装到User对象身上
        User user = new User();
        try {
            BeanUtils.populate(user, request.getParameterMap());

            //2 检验用户
            Map<String, String> map = user.checkCust();
            if(map.size() > 0){
                request.setAttribute("map",map);
                request.getRequestDispatcher("/regist.jsp").forward(request, response);
                return;
            }

            //对密码进行加密  md5加密
            user.setPassword(MD5Utils.md5( user.getPassword() ));
            //3 添加
            UserService userService = new UserService();
            userService.addUser(user);

            //4 重定向到首页
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }catch (Exception e){

        }

        //2 插入数据库

        //3 页面跳转
    }
}
